"""
User Model
用户数据模型
"""

import uuid

from sqlalchemy import Column, String, DateTime, Integer, Boolean, Text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from ..core.database import Base


class User(Base):
    """用户模型"""

    __tablename__ = "users"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    email = Column(String(255), unique=True, nullable=False, index=True)
    username = Column(String(50), unique=True, nullable=False, index=True)
    full_name = Column(String(100), nullable=True)
    hashed_password = Column(String(255), nullable=False)

    # 用户状态
    role = Column(String(20), nullable=False, default="user")  # user, admin
    status = Column(
        String(20), nullable=False, default="active"
    )  # active, locked, banned

    # 个人资料
    avatar_url = Column(String(500), nullable=True)
    bio = Column(Text, nullable=True)

    # 使用限制
    daily_generation_limit = Column(Integer, default=50)
    storage_quota_mb = Column(Integer, default=1024)
    used_storage_mb = Column(Integer, default=0)

    # 安全设置
    email_verified = Column(Boolean, default=False)
    two_factor_enabled = Column(Boolean, default=False)

    # 时间戳
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    last_login_at = Column(DateTime, nullable=True)

    # 关系
    settings = relationship("UserSettings", back_populates="user", uselist=False, cascade="all, delete-orphan")
    creation_requests = relationship("CreationRequest", back_populates="user", cascade="all, delete-orphan")
    generated_contents = relationship("GeneratedContent", back_populates="user", cascade="all, delete-orphan")
    folders = relationship("Folder", back_populates="user", cascade="all, delete-orphan")
    task_queues = relationship("TaskQueue", back_populates="user", cascade="all, delete-orphan")
    system_logs = relationship("SystemLog", back_populates="user")

    def __repr__(self):
        return f"<User(id={self.id}, username={self.username}, email={self.email})>"

    @property
    def is_active(self):
        """是否激活用户"""
        return self.status == "active"

    @property
    def is_admin(self):
        """是否管理员"""
        return self.role == "admin"

    @property
    def storage_usage_percent(self):
        """存储使用率"""
        if self.storage_quota_mb == 0:
            return 0
        return (self.used_storage_mb / self.storage_quota_mb) * 100

    def can_generate_content(self):
        """检查是否可以生成内容"""
        return self.status == "active" and self.storage_usage_percent < 100
